package com.gy.zpchat.ui.chat.peer;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;


import java.util.ArrayList;
import java.util.Collections;

import im.zego.zim.callback.ZIMUsersInfoQueriedCallback;
import im.zego.zim.entity.ZIMError;
import im.zego.zim.entity.ZIMErrorUserInfo;
import im.zego.zim.entity.ZIMUserFullInfo;
import im.zego.zim.enums.ZIMConversationType;
import im.zego.zim.enums.ZIMErrorCode;
import com.gy.zpchat.R;
import com.gy.zpchat.SDKManager;
import com.gy.zpchat.ui.BaseActivity;

public class ZIMPeerChatCreateActivity extends BaseActivity {

    private TextView userIDText;

    public static void actionStart(Activity activity) {
        Intent intent = new Intent(activity, ZIMPeerChatCreateActivity.class);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_peer_chat_create);
        userIDText = findViewById(R.id.user_id);

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void onCreatePeerChat(View view) {
        String userID = userIDText.getText().toString();
        SDKManager.sharedInstance().queryUsersInfo(Collections.singletonList(userID),true, new ZIMUsersInfoQueriedCallback() {
            @Override
            public void onUsersInfoQueried(ArrayList<ZIMUserFullInfo> userList, ArrayList<ZIMErrorUserInfo> errorUserList, ZIMError errorInfo) {
                if (errorInfo.code != ZIMErrorCode.SUCCESS) {
                    Toast.makeText(ZIMPeerChatCreateActivity.this, "Failed to query user info, error:" + errorInfo.code, Toast.LENGTH_SHORT).show();
                    return;
                }
                for (ZIMUserFullInfo userInfo : userList) {
                    if (userInfo.baseInfo.userID.equals(userID)) {
                        SDKManager.sharedInstance().insertSystemMessage("创建单聊成功", ZIMConversationType.PEER,userInfo.baseInfo.userID);
                        ZIMPeerChatActivity.actionStart(ZIMPeerChatCreateActivity.this, userInfo.baseInfo.userID, userInfo.baseInfo.userName,"");
                        return;
                    }
                }
            }
        });

    }
}
